package com.example._03vehicle.controller;

import com.example._03vehicle.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.UUID;


@Slf4j
@RestController
@Api(tags ="04.文件上传模块")
@RequestMapping("/v1/file/")
public class UplodaController {
    @ApiOperation(value = "上传文件")
    @PostMapping("upload")
    @ApiOperationSupport(order=10)
    public JsonResult upload(MultipartFile file){
        String fileName=file.getOriginalFilename();//获取文件名
        log.debug("上传文件名：{}",fileName);
        //获取文件名的后缀
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        //生成随机文件名且唯一
        String uuid=(UUID.randomUUID()+suffix);
        log.debug(uuid);
        //自定义日期格式的路径：yyyy/MM/dd
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String path=simpleDateFormat.format(new java.util.Date());
        log.debug("文件上传路径：{}",path);
//        try {
//            file.transferTo(new java.io.File("d:/files/"+path,uuid));
//        } catch (Exception e) {
//            log.error("文件上传失败：{}",e.getMessage());
//            return JsonResult.fail();
//        }
        //定义静态资源路径
        String staticPath="d:/files";
        //创建目录并保存文件
        java.io.File filePath=new java.io.File(staticPath+path);
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        //保存文件到服务器
        String filePathName=filePath+"/"+uuid;
        try {
            //前端返回data数据内容为路径，并拼接路径显示图片
            file.transferTo(new java.io.File(filePathName));
            return JsonResult.success(filePathName);
        } catch (Exception e) {
            log.error("文件上传失败：{}",e.getMessage());
            return JsonResult.fail();
        }

    }
}
